package org.hhchat.others.ali;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created this one by HMH on 2017/8/25.
 */
public class MockStackTest {
    private Lock lock = new ReentrantLock();
    private Condition cond = lock.newCondition();
    private List<Integer> list = new ArrayList<Integer>();
    public void push(int value) {
        try {
            lock.lock();
            list.add(value);
            cond.signal();
        } finally {
            lock.unlock();
        }
    }

    public int pop() throws InterruptedException {
        try {
            lock.lock();
            if (list.size() <= 0) {
                cond.await();
            }
            return list.remove(list.size() - 1);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final MockStackTest myStack = new MockStackTest();
        ExecutorService exeSrv = Executors.newFixedThreadPool(5);
        final StringBuffer sb = new StringBuffer();
        ArrayList<Future<?>> futureList = new ArrayList<Future<?>>();
        try {
            for (int i = 0; i < 5; i++) {
                futureList.add(exeSrv.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sb.append(myStack.pop());
                        } catch (InterruptedException e) {}
                    }
                }));
            }
            for (int i = 0; i < 5; i++) {
                myStack.push(i);
            }
            for (Future<?> future : futureList) {
                try {
                    future.get();
                } catch (ExecutionException | InterruptedException e) {}
            }
            System.out.println(sb.toString());
        } finally {
            exeSrv.shutdown();
        }
    }
}